/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: dings
 * Date: 2024-07-08
 * Time: 15:07
 */

class ListNode {
     int val;
     ListNode next;
     ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        //当head为空时
        if(head == null) {
            return head;
        }

        //双指针法求解
        ListNode prev = head;
        ListNode cur = head.next;


        while (cur != null) {
            //判断当前节点的值是否为要删除的val值
            if (cur.val == val) {//若是，删除节点
                cur = cur.next;
                prev.next = cur;
            }else {//若不是，均向后移动
                cur = cur.next;
                prev = prev.next;
            }
        }
        //判断第一个节点的值是否我要删除的val值。
        if (head.val == val) {
            head = head.next;
        }
        //返回删除后的头结点
        return head;
    }
}
public class Test {
    public static void main(String[] args) {

    }
}
